package com.study.example.gameserver.hotfix;

import com.sparrow.common.thread.factory.SimpleThreadFactory;
import com.sparrow.event.annotation.EventReceiver;
import com.study.example.gameserver.base.ConfigService;
import com.study.example.gameserver.event.ServerInitEvent;
import com.study.example.gameserver.serverinfo.service.ServerInfoService;
import com.study.example.gameserver.serverinfo.domain.ServerInfoKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 热修复
 */
@Component
public class HotFixService implements DisposableBean {
    private static Logger logger = LoggerFactory.getLogger(HotFixService.class);

    @Autowired
    private ServerInfoService serverInfoService;
    @Autowired
    private ConfigService configService;

    private ScheduledExecutorService scheduledExecutor;

    @EventReceiver
    public void start(ServerInitEvent initEvent) {
        scheduledExecutor = Executors.newSingleThreadScheduledExecutor(new SimpleThreadFactory("HotFix"));
        scheduledExecutor.scheduleWithFixedDelay(() -> {
            hotFix();
        }, 1, 1, TimeUnit.SECONDS);
    }

    public void hotFix() {
        int lastVersion = 0;
        String value = serverInfoService.getValue(configService.getServerId(), ServerInfoKey.hotSwapVer);
        if (value != null) {
            lastVersion = Integer.parseInt(value);
        }
        int version = 2025052801;
        if (lastVersion < version) {
            serverInfoService.setValue(configService.getServerId(), ServerInfoKey.hotSwapVer, String.valueOf(version));
            try {
                System.out.println("i am");
            } catch (Exception e) {
                logger.error("", e);
            }
            logger.info("hot fix finish version:{} server:{}", version, configService.getServerId());
        }
    }

    @Override
    public void destroy() throws Exception {
        if (scheduledExecutor != null) {
            scheduledExecutor.shutdown();
        }
        logger.info("HotFixService关闭");
    }
}
